package com.lagou;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

/**
 * 测试事务
 */
public class Test_Transaction {

    public static void main(String[] args) throws InterruptedException {
        Jedis jedis = new Jedis("192.168.106.128",6379);
        int yue = Integer.parseInt(jedis.get("yue"));
        int zhichu = 10;
        // 监控余额
        jedis.watch("yue");
        // 模拟网络延迟
        Thread.sleep(5000);

        if(yue<zhichu){
            // 解除余额
            jedis.unwatch();
            System.out.println("余额不足");
        }else{
            // 开启事务
            Transaction transaction = jedis.multi();
            transaction.decrBy("yue",zhichu);
            transaction.incrBy("zhichu",zhichu);
            // 执行事务
            transaction.exec();
            System.out.println("余额:"+jedis.get("yue"));
            System.out.println("支出:"+jedis.get("zhichu"));
        }
    }

}
